package com.xx.happychatboot.serve.user.service.impl;

import com.xx.happychatboot.base.vo.response.ResponseDate;
import com.xx.happychatboot.middleware.netty.domain.enums.RocketMqTypeEnum;
import com.xx.happychatboot.middleware.rocketmq.constants.RocketMqConstants;
import com.xx.happychatboot.middleware.rocketmq.domain.dto.RocketMqCommonDto;
import com.xx.happychatboot.middleware.rocketmq.utils.RocketMqProducer;
import com.xx.happychatboot.serve.room.service.IRoomService;
import com.xx.happychatboot.serve.user.domain.entity.UserApply;
import com.xx.happychatboot.serve.user.domain.entity.UserFriend;
import com.xx.happychatboot.serve.user.domain.enums.ApplyReadStatusEnum;
import com.xx.happychatboot.serve.user.domain.enums.ApplyStatusEnum;
import com.xx.happychatboot.serve.user.domain.enums.ApplyTypeEnum;
import com.xx.happychatboot.serve.user.domain.vo.response.NewFriendVo;
import com.xx.happychatboot.serve.user.mapper.UserApplyMapper;
import com.xx.happychatboot.serve.user.mapper.UserFriendMapper;
import com.xx.happychatboot.serve.user.service.IUserApplyService;
import com.xx.happychatboot.serve.user.service.IUserFriendService;
import io.mybatis.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class UserApplyServiceImpl extends AbstractService<UserApply, Long, UserApplyMapper> implements IUserApplyService {
    @Autowired
    private UserApplyMapper userApplyMapper;

    @Autowired
    private RocketMqProducer rocketMqProducer;

    @Autowired
    private UserFriendMapper userFriendMapper;

    @Autowired
    private IUserFriendService userFriendService;

    @Autowired
    private IRoomService roomService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDate applyFriend(UserApply userApply) {
        if (Objects.isNull(userApply)
                || Objects.isNull(userApply.getUid())
                || Objects.isNull(userApply.getTargetId())) {
            return ResponseDate.fail("申请失败，请联系管理员");
        }

        // 判断是否已经申请过了
        UserApply select = new UserApply();
        select.setUid(userApply.getUid());
        select.setTargetId(userApply.getTargetId());
        Optional<UserApply> applyOptional = userApplyMapper.selectOne(select);
        // 如果申请过则更新msg即可
        if (applyOptional.isPresent()) {
            UserApply apply = applyOptional.get();
            apply.setMsg(userApply.getMsg());
            apply.setUpdateTime(new Date());
            userApplyMapper.updateByPrimaryKeySelective(apply);
        } else {
            userApply.setCreateTime(new Date());
            userApply.setUpdateTime(new Date());
            userApply.setType(ApplyTypeEnum.ADD_FRIEND.getCode());
            userApply.setReadStatus(ApplyReadStatusEnum.UNREAD.getCode());
            userApply.setStatus(ApplyStatusEnum.WAIT_APPROVAL.getCode());
            userApplyMapper.insert(userApply);
        }
        // 发送添加好友请求
        RocketMqCommonDto rocketMqCommonDto = new RocketMqCommonDto();
        rocketMqCommonDto.setCode(RocketMqTypeEnum.ADD_FRIEND.getCode());
        rocketMqCommonDto.setUid(userApply.getTargetId());
        String key = RocketMqConstants.ADD_FRIEND_KEY + userApply.getTargetId();
        rocketMqProducer.sendSecureMsg(RocketMqConstants.ADD_FRIEND_TOPIC, rocketMqCommonDto, key);
        return ResponseDate.success("好友申请已发送");
    }

    /**
     * 获取好友申请列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<UserApply> getApplyList(Long userId) {
        if (Objects.isNull(userId)) {
            throw new RuntimeException("用户id不可为空");
        }
        UserApply select = new UserApply();
        select.setTargetId(userId);
        return userApplyMapper.selectList(select);
    }

    @Override
    public ResponseDate getApplyListCount(Long userId) {
        if (Objects.isNull(userId)) {
            return ResponseDate.fail("用户ID不能为空");
        }
        List<UserApply> userApplyList = getUserApplies(userId);
        return ResponseDate.success(userApplyList.size());
    }

    @Override
    public List<UserApply> getUserApplies(Long userId) {
        UserApply select = new UserApply();
        select.setTargetId(userId);
        select.setReadStatus(ApplyReadStatusEnum.UNREAD.getCode());
        select.setStatus(ApplyStatusEnum.WAIT_APPROVAL.getCode());
        List<UserApply> userApplyList = userApplyMapper.selectList(select);
        return userApplyList;
    }

    @Override
    public List<NewFriendVo> getNewFriendList(Long userId) {
        if (Objects.isNull(userId)) {
            return new ArrayList<>();
        }

        return userApplyMapper.selectNewFriendList(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDate agreeAddFried(UserApply userApply) {
        if (Objects.isNull(userApply.getId())) {
            return ResponseDate.fail("出现异常，请联系管理员");
        }
        Optional<UserApply> applyOptional = userApplyMapper.selectByPrimaryKey(userApply.getId());
        if (!applyOptional.isPresent()) {
            return ResponseDate.fail("出现异常，请联系管理员");
        }
        UserApply apply = applyOptional.get();

        apply.setStatus(2);
        userApplyMapper.updateByPrimaryKeySelective(apply);

        // 添加好友 ---> 添加两条信息
        UserFriend self = userFriendService.buildNewFriend(apply.getUid(), apply.getTargetId());

        UserFriend friend = userFriendService.buildNewFriend(apply.getTargetId(), apply.getUid());

        userFriendMapper.insert(self);
        userFriendMapper.insert(friend);

        // 创建房间
        roomService.creatRoom(apply.getUid(), apply.getTargetId());

        // 使用消息队列处理好友添加
        // 发送添加好友请求
        String key = RocketMqConstants.AGREE_ADD_FRIEND_KEY + apply.getUid();
        rocketMqProducer.buildAndSendSecureMsg(
                RocketMqTypeEnum.AGREE_ADD_FRIEND.getCode(),
                apply.getUid(),
                key,
                RocketMqConstants.AGREE_ADD_FRIEND_TOPIC);

        String key2 = RocketMqConstants.AGREE_ADD_FRIEND_KEY + apply.getTargetId();
        rocketMqProducer.buildAndSendSecureMsg(
                RocketMqTypeEnum.AGREE_ADD_FRIEND.getCode(),
                apply.getTargetId(),
                key2,
                RocketMqConstants.AGREE_ADD_FRIEND_TOPIC);

        return ResponseDate.success("已同意好友申请");
    }
}
